package com.aliyun.messagemgt.web.controller.query;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.messagemgt.application.service.MessageRecordService;
import com.aliyun.messagemgt.application.service.MessageTemplateService;
import com.aliyun.messagemgt.common.dto.response.ResultMap;
import com.aliyun.messagemgt.dto.query.MessageRecordQueryDTO;
import com.aliyun.messagemgt.feignapi.QueryApiHttp;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;

@Service
public class QueryController implements QueryApiHttp {


    @Resource
    MessageTemplateService messageTemplateService;

    @Resource
    MessageRecordService messageRecordService;

    public ResultMap<JSONObject> templateCount() {
        return new ResultMap<>(getMetrics("messageTemplateCount", "消息模板数", "当前系统消息模板数", messageTemplateService.queryTemplateCount(), "个"));
    }

    @Override
    public ResultMap<JSONObject> messageRecordCount() {
        return new ResultMap<>(getMetrics("messageCount", "消息总发送数", "当前系统消息组件总发送的消息数", messageRecordService.countMessageRecordQuery(new MessageRecordQueryDTO()), "条"));
    }

    private JSONObject getMetrics(String metricCode, String metricName, String metricNote, Long number, String unit) {
        JSONObject object = new JSONObject();
        object.put("code", 0);
        object.put("ok", true);
        JSONObject data = new JSONObject();
        data.put("componentCode", "message");
        data.put("metricCode", metricCode);
        data.put("metricName", metricName);
        data.put("metricNote", metricNote);
        data.put("metricUnit", unit);
        JSONObject metrics = new JSONObject();
        data.put("metrics", Collections.singletonList(metrics));
        metrics.put("metricValue", number);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String currentTime = LocalDateTime.now().format(formatter);
        metrics.put("metricTime", currentTime);
        object.put("data", data);
        return object;
    }
}
